package com.kzd.gtboon.main.web

import android.view.LayoutInflater
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebView
import com.kzd.gtboon.callback.AppWebViewClient
import com.kzd.gtboon.custom.createViewWeb
import com.kzd.gtboon.databinding.ActivityWebViewBinding
import com.kzd.gtboon.main.KEY_RICH_TEXT_TITLE
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.owner.OwnerViewBindingActivity

open class WebViewActivity : OwnerViewBindingActivity<ActivityWebViewBinding>() {


    private val mTitle: String?
        get() = intent?.extras?.getString(KEY_RICH_TEXT_TITLE)

    val mWebView: WebView by lazy {
        createViewWeb(context = this).apply { webViewClient = AppWebViewClient() }
    }

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flWebViewBar
            lightMode = true
        }
        super.initStatusBar(statusBar)
    }

    override val inflate: (LayoutInflater) -> ActivityWebViewBinding
        get() = ActivityWebViewBinding::inflate

    override fun initView() {
        mViewBinding.flWebViewBar.setTitleTextContent(mTitle)
        mViewBinding.flWebViewBar.visibility = if (mTitle.isNullOrEmpty())
            View.GONE else View.VISIBLE
        mViewBinding.mWebViewBody.addView(mWebView)
    }

    override fun onResume() {
        super.onResume()
        mWebView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mWebView.onPause()
    }

    override fun onDestroy() {
        if (mWebView.windowToken != null) {
            mViewBinding.mWebViewBody.removeView(mWebView)
        }
        mWebView.clearHistory()
        mWebView.destroy()
        CookieManager.getInstance().removeAllCookies(null)
        CookieManager.getInstance().flush()
        super.onDestroy()
    }

    fun WebView.loadDataWithBaseURL(content: String) {
        loadDataWithBaseURL((null), content, ("text/html"), ("utf-8"), (null))
    }
}